package com.zhxymm.book.controllers;

import com.zhxymm.book.entity.Borrow;
import com.zhxymm.book.entity.UserOne;
import com.zhxymm.book.service.BorrowService;
import com.zhxymm.book.service.UserOneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("userOnes")
public class UserOneController {

    @Autowired
    UserOneService userOneService;

    @Autowired
    BorrowService borrowService;

    @GetMapping
    public String displayUserOnes(Model model){
        List<UserOne> userOnes = userOneService.getAll();
        model.addAttribute("userOnes",userOnes);
        return "userOnes/list-userOnes";
    }

    @GetMapping("/new")
    public String displayUserOneForm(Model model){
        UserOne aUserOne = new UserOne();
        List<Borrow> borrows = borrowService.getAll();
        model.addAttribute("userOne",aUserOne);
        model.addAttribute("allBorrows",borrows);
        return "userOnes/new-userOne";
    }

    @PostMapping("/save")
    public String createUserOne(Model model, @RequestParam List<Long> borrows,UserOne userOne){
        userOneService.save(userOne);
        return "redirect:/userOnes";
    }

    @GetMapping("update")
    public String displayUserOneUpdateForm(@RequestParam("id")long theId,Model model){
        UserOne theUserOne = userOneService.findByUserId(theId);
        model.addAttribute("userOne",theUserOne);
        return "userOnes/new-userOne";
    }

    @GetMapping("/delete")
    public String deleteBorrow(@RequestParam("id")long theId,Model model){
        UserOne theUserOne = userOneService.findByUserId(theId);
        userOneService.delete(theUserOne);
        return "redirect:/userOnes";
    }
}
